package com.gtt.lazy.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.FileUtils;

/**
 * 图片工具
 * 
 * @author 高甜甜
 * @date 2009-7-9
 */
public class ImageUtil {

	/**
	 * 存储图片
	 * 
	 * @param sid
	 * @param fileName
	 * @param upload
	 * @param imagePath
	 * @return
	 */
	public static String store(int sid, String fileName, File upload,
			String imagePath) {
		if (upload == null)
			return "";

		String name = sid + "." + getSuffix(fileName);
		File file = new File(imagePath + File.separator + name);
		try {
			FileUtils.copyFile(upload, file);
			return name;
		} catch (IOException e) {
			return "";
		}
	}

	/**
	 * 获取文件后缀
	 * 
	 * @param fileName
	 * @return
	 */
	public static String getSuffix(String fileName) {
		return fileName.substring(fileName.lastIndexOf(".") + 1);
	}

	public static void delete(String imagePath, String image)
			throws IOException {
		FileUtils.forceDelete(new File(imagePath + File.separator + image));
	}

	public static InputStream get(String image, String imagePath) {
		try {
			return new FileInputStream(imagePath + File.separator + image);
		} catch (FileNotFoundException e) {
			return null;
		}
	}

	public static void move(String imagePath, String image, String imageBakPath)
			throws IOException {
		FileUtils.copyFileToDirectory(new File(imagePath + File.separator
				+ image), new File(imageBakPath));
		FileUtils.forceDelete(new File(imagePath + File.separator + image));
	}

}
